
#import "Data.h"

#define kLampDataLamps @"lamps"
#define kLampDataWattLumen @"watt_lumen"
#define kLampDataWattLumenTypeClassic @"classic"
#define kLampDataWattLumenTypeHalogen @"halogen"
#define kLampDataWattLumenTypeReflector12v @"reflector12v"
#define kLampDataWattLumenTypeReflector230v @"reflector230v"


@interface Data ()

@property (nonatomic, readonly) NSDictionary *wattToLumenTables;

@end

@implementation Data

-(instancetype)init
{
    self = [super init];
    if (self) {
        NSError *error = nil;
        NSString *path = [[NSBundle mainBundle] pathForResource:@"lampdata" ofType:@"json"];
        NSData *jsonData = [NSData dataWithContentsOfFile:path];
        NSDictionary *lampData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        NSAssert(error == nil, @"Error in JSON data");
        
        _lampList = lampData[kLampDataLamps];
        _wattToLumenTables = lampData[kLampDataWattLumen];
    }
    return self;
}

-(NSDictionary *)wattToLumenTableForLampTypeWithKey:(NSString *)lampTypeKey
{
    return self.wattToLumenTables[lampTypeKey];
}

-(NSString *)lumenStringFromWattValue:(NSInteger)watt lampTypeWithKey:(NSString *)lampTypeKey
{
    NSDictionary *conversionTable = self.wattToLumenTables[lampTypeKey];
    NSArray *range = conversionTable[[@(watt) stringValue]];
    
    NSAssert(range != nil, @"Could not find effect %ld W for '%@' in wattToLumenTable", (long)watt, lampTypeKey);
    
    NSInteger from = [range[0] integerValue];
    NSInteger to = [range[1] integerValue];

    return from == to ? [@(from) stringValue] : [NSString stringWithFormat:@"%ld–%ld", (long)from, (long)to];
}

#pragma mark - Singleton stuff
+(Data *)sharedInstance
{
    static Data *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ sharedInstance = [[Data alloc] init]; });
    return sharedInstance;
}
@end

